<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\yb\ActivityModel;
use App\Models\yb\SettingModel;
use App\Models\yb\UserAddressModel;
use App\Models\yb\UserModel;
use App\Models\yb\GoodsOrderModel;
use App\Models\yb\UserWalletRecordModel;
use App\Models\yb\UserWaterTicketModel;
use Illuminate\Http\Request;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;


class UserController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
//    public function __construct()
//    {
//        $this->middleware('auth:api', ['except' => ['preview']]);
//    }

    /**
     * Get a JWT via given credentials.
     *  地址列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserAddressListing(Request $request){

        $openid = $request->post('openid');
        if(empty($openid)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }
        $user_data = UserModel::where(['openid'=>$openid])->first();

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $title = $request->post('title');
        
        if(empty($user_data)){
            return response()->json(['code'=>'200','msg' => '请求成功','data'=>array()]);
        }

        $data = UserAddressModel::where(['user_id'=>$user_data['id']])->when($title,function ($query,$title){
            $query->where('address','like',"%".$title."%");
        })->orderBy('is_default','desc')->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);
    }

    /**
     * Get a JWT via given credentials.
     * 地址添加/编辑
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserAddressAdd(Request $request){

        $openid = $request->post('openid');
        if(empty($openid)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $address_id =  $request->post('address_id');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        $name = $request->post('name');

        $mobile = $request->post('mobile');

        $stair_type = $request->post('stair_type');

        $floor = $request->post('floor');

        $locating_address = $request->post('locating_address');

        $address = $request->post('address');

        $house_number = $request->post('house_number');

        $is_default = $request->post('is_default');

        $latitude = $request->post('latitude');

        $longitude = $request->post('longitude');

        Log::info($request->input());
        if($is_default == 1){
            UserAddressModel::where(['user_id'=>$user_data['id'],'is_default'=>1])->update(['is_default'=>0]);
        }

        $data = [
            'name' => $name,
            'openid'=> $openid,
            'user_id' => $user_data['id'],
            'mobile' => $mobile,
            'stair_type' => $stair_type,
            'floor' => $floor,
            'locating_address' => $locating_address,
            'address' => $address,
            'house_number' => $house_number,
            'is_default' => $is_default,
            'latitude' => $latitude,
            'longitude' => $longitude,
        ];

        if(!empty($address_id)){
            UserAddressModel::where(['id'=>$address_id])->update($data);
        }else{
            UserAddressModel::insert($data);
        }

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }


    /**
     * Get a JWT via given credentials.
     * 地址删除
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserAddressDel(Request $request)
    {

        $openid = $request->post('openid');

        if (empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $address_id =  $request->post('address_id');
        
        $goods_data = GoodsOrderModel::where(['address_id'=>$address_id])->first();
        
        if(!empty($goods_data)){
            return response()->json(['code'=>'203','msg' => '该地址不可删除']);
        }
        UserAddressModel::where(['id'=>$address_id])->delete();
        
        

        return response()->json(['code'=>'200','msg' => '请求成功']);

    }


    /**
     * Get a JWT via given credentials.
     * 地址详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function UserAddressDetail(Request $request)
    {

        $address_id =  $request->post('address_id');

        $data = UserAddressModel::where(['id'=>$address_id])->first();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }


    /**
     * Get a JWT via given credentials.
     * 我的
     * @return \Illuminate\Http\JsonResponse
     */
    public function My(Request $request)
    {

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if (empty($user_data)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }
        $user_water_ticket = UserWaterTicketModel::where(['user_id'=>$user_data['id']])->sum('number');

        $user_activity = ActivityModel::where(['is_my'=>1,'status'=>1])->first();
        if(!empty($user_activity)){
            $user_activity['cover'] = env('OSS_URL').$user_activity['cover'];
        }

        $data['time'] = date('Y-m-d',time());
        $data['user_water_ticket'] = $user_water_ticket;
        $data['user_activity'] = $user_activity;
        $data['count']['order_delivery_count'] = GoodsOrderModel::where(['user_id'=>$user_data['id'],'status'=>1])->count();
        $data['count']['order_service_count'] = GoodsOrderModel::where(['user_id'=>$user_data['id'],'status'=>3])->count();
        $data['count']['order_complete_count'] = GoodsOrderModel::where(['user_id'=>$user_data['id'],'status'=>4])->count();
        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     * 分享
     * @return \Illuminate\Http\JsonResponse
     */
    public function ShareQrcode(Request $request)
    {

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid' => $openid])->first();

        if (empty($user_data)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        if(empty($user_data['share_qrcode'])){
            $config = [
                'app_id' => env('WECHAT_CLIENT_APP_ID'),  // 这里需要自行修改
                'secret' => env('WECHAT_CLIENT_APP_SECRET'),  // 这里需要自行修改
            ];

            $app = Factory::miniProgram($config);

            //二维码
            $filename=time().'_wx.jpg';
            //判断file文件中是否存在数据库当中
            $qr_path = './qrcode';
            $qr_paths = './qrcode';
            
            $path='pages/index/home';
            $param='openid='.$user_data['id'];
          
            $response = $app->app_code->getUnlimit($param, [
                'page'  => $path,
                'width' => 600,
            ]);
            // $response = $app->app_code->getQrCode('/pages/index/home?openid='.$openid);
   
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $resfilename = $response->saveAs($qr_path,$filename);
                $resfilename= env('APP_URL').trim($qr_paths.'/'.$resfilename,'.');
            }

            UserModel::where(['id' => $user_data['id']])->update(['share_qrcode'=>$resfilename]);

            $user_data['share_qrcode'] = $resfilename;

        }

        if(empty($user_data['share_number'])){
    
            $info = $this->createInvitecode();

            UserModel::where(['id' => $user_data['id']])->update(['share_number'=>$info]);
            $user_data['share_number'] = $info;
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$user_data]);

    }
    
    public function createInvitecode() {
        // 生成字母和数字组成的6位字符串
    
        $str = range('A', 'Z');
        // 去除大写的O，以防止与0混淆 
        unset($str[array_search('O', $str)]);
        $arr = array_merge(range(0, 9), $str);
        shuffle($arr);
        $invitecode = '';
        $arr_len = count($arr);
        for ($i = 0; $i < 4; $i++) {
            $rand = mt_rand(0, $arr_len - 1);
            $invitecode .= $arr[$rand];
        }
    
        return $invitecode;
    
    }
    /**
     * Get a JWT via given credentials.
     * 推广积分
     * @return \Illuminate\Http\JsonResponse
     */
    public function ShareWallet(Request $request)
    {

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid' => $openid])->first();

        if (empty($user_data)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $setting_data = SettingModel::select(['minimum','withdrawal_rule','invitation_reward'])->first();

        $user_data['minimum'] = $setting_data['minimum'];

        $user_data['withdrawal_rule'] = $setting_data['withdrawal_rule'];

        $user_data['invitation_reward'] = $setting_data['invitation_reward'];
        
        $user_data['guests_number'] = UserModel::where(['inviter_user_id'=>$user_data['id']])->count();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$user_data]);

    }

    /**
     * Get a JWT via given credentials.
     * 积分明细
     * @return \Illuminate\Http\JsonResponse
     */
    public function WalletRecord(Request $request)
    {

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid' => $openid])->first();

        if (empty($user_data)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $user_wallet_record_data = UserWalletRecordModel::where(['user_id'=>$user_data['id']])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$user_wallet_record_data]);

    }

    /**
     * Get a JWT via given credentials.
     * 提现
     * @return \Illuminate\Http\JsonResponse
     */
    public function WalletWithdrawal(Request $request)
    {

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid' => $openid])->first();

        if (empty($user_data)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $amount = $request->post('amount', 0);

        $setting_data = SettingModel::select(['minimum'])->first();

        if($amount<$setting_data['minimum']){
            return response()->json(['code' => '203', 'msg' => '最低金额不能低于'.$setting_data['minimum']]);
        }

        if($amount<$user_data['surplus_points']){
            return response()->json(['code' => '203', 'msg' => '余额不足']);
        }

        return response()->json(['code' => '203', 'msg' => '暂未开放']);


        return response()->json(['code'=>'200','msg' => '请求成功']);

    }

    /**
     * Get a JWT via given credentials.
     * 提现规则
     * @return \Illuminate\Http\JsonResponse
     */
    public function WalletRule(Request $request)
    {

        $setting_data = SettingModel::select(['withdrawal_rule'])->first();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$setting_data]);

    }

   /**
     * Get a JWT via given credentials.
     * 修改用户昵称
     * @return \Illuminate\Http\JsonResponse
     */
    public function UpdateUser(Request $request)
    {

        $openid = $request->post('openid');

        $nickname = $request->post('nickname');

        $avatar = $request->post('avatar');

        $user_data = UserModel::where(['openid' => $openid])->first();

        if (empty($user_data)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        UserModel::where(['openid' => $openid])->update([
            'nickname'=>$nickname,
            'avatar'=>$avatar
        ]);
        $user_data['nickname']=$nickname;
        $user_data['avatar']=$avatar;

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$user_data]);

    }


}
